<template>
  <div class="image-loader-container">
    <img v-if="!isDone" :src="placeholder" class="placeholder" :alt="placeholder" />
    <img
      :src="src"
      :alt="src"
      :style="{ opacity: originOpacity, transition: `${duration}ms` }"
      @load="handleLoad"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue'

export default defineComponent({
  props: {
    src: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      required: true
    },
    duration: {
      type: Number,
      default: 500
    }
  },
  emits: ['load'],
  setup(props, { emit }) {
    // 原图是否加载完
    const originLoaded = ref(false)
    // 是否都准备就绪
    const isDone = ref(false)
    const originOpacity = computed(() => (originLoaded.value ? 1 : 0))

    const handleLoad = () => {
      originLoaded.value = true
      setTimeout(() => {
        isDone.value = true
        emit('load')
      }, props.duration)
    }
    return {
      originLoaded,
      isDone,
      originOpacity,
      handleLoad
    }
  }
})
</script>

<style lang="less" scoped>
@import '@/styles/mixin.less';
.image-loader-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;

  img {
    .self-fill();
    object-fit: cover;
  }

  .placeholder {
    filter: blur(2vw);
  }
}
</style>